#include "wifi_board.h"

#include <esp_http.h>
#include <esp_log.h>
#include <esp_mqtt.h>
#include <esp_udp.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <ssid_manager.h>
#include <tcp_transport.h>
#include <tls_transport.h>
#include <web_socket.h>
#include <wifi_configuration_ap.h>
#include <wifi_station.h>

#include "assets/lang_config.h"
#include "settings.h"
#include "system_info.h"

static const char* TAG = "WifiBoard";

WifiBoard::WifiBoard() {
    Settings settings("wifi", true);
    wifi_config_mode_ = settings.GetInt("force_ap") == 1;
    if (wifi_config_mode_) {
        ESP_LOGI(TAG, "force_ap is set to 1, reset to 0");
        settings.SetInt("force_ap", 0);
    }
}

std::string WifiBoard::GetBoardType() { return "wifi"; }

void WifiBoard::EnterWifiConfigMode() {
    auto& wifi_ap = WifiConfigurationAp::GetInstance();
    wifi_ap.SetLanguage(Lang::CODE);
    wifi_ap.SetSsidPrefix("Xiaozhi");
    wifi_ap.Start();

    SetState(WifiState::ConfigMode);
    // Wait forever until reset after configuration
    while (true) {
        int free_sram = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
        int min_free_sram = heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL);
        ESP_LOGI(TAG, "Free internal: %u minimal internal: %u", free_sram, min_free_sram);
        vTaskDelay(pdMS_TO_TICKS(10000));
    }
}

void WifiBoard::StartNetwork() {
    // User can press BOOT button while starting to enter WiFi configuration mode
    if (wifi_config_mode_) {
        EnterWifiConfigMode();
        return;
    }

    // If no WiFi SSID is configured, enter WiFi configuration mode
    auto& ssid_manager = SsidManager::GetInstance();
    auto ssid_list = ssid_manager.GetSsidList();
    if (ssid_list.empty()) {
        wifi_config_mode_ = true;
        EnterWifiConfigMode();
        return;
    }

    auto& wifi_station = WifiStation::GetInstance();
    wifi_station.OnScanBegin([this]() { SetState(WifiState::Scanning); });
    wifi_station.OnConnect([this](const std::string& ssid) { SetState(WifiState::Connecting); });
    wifi_station.OnConnected([this](const std::string& ssid) { SetState(WifiState::Connected); });
    wifi_station.Start();

    // Try to connect to WiFi, if failed, launch the WiFi configuration AP
    if (!wifi_station.WaitForConnected(60 * 1000)) {
        wifi_station.Stop();
        wifi_config_mode_ = true;
        EnterWifiConfigMode();
        return;
    }
}

Http* WifiBoard::CreateHttp() { return new EspHttp(); }

WebSocket* WifiBoard::CreateWebSocket() {
    Settings settings("websocket", false);
    std::string url = settings.GetString("url");
    if (url.find("wss://") == 0) {
        return new WebSocket(new TlsTransport());
    } else {
        return new WebSocket(new TcpTransport());
    }
    return nullptr;
}

Mqtt* WifiBoard::CreateMqtt() { return new EspMqtt(); }

Udp* WifiBoard::CreateUdp() { return new EspUdp(); }

Board::SinalStrength WifiBoard::GetWiFiStrength() {
    if (wifi_config_mode_) {
        return WifiBoard::SinalStrength::ConfigAp;
    }

    auto& wifi_station = WifiStation::GetInstance();
    if (!wifi_station.IsConnected()) {
        return WifiBoard::SinalStrength::None;
    }

    int8_t rssi = wifi_station.GetRssi();
    if (rssi >= -60) {
        return Board::SinalStrength::Excellent;
    } else if (rssi >= -70) {
        return Board::SinalStrength::Good;
    } else {
        return Board::SinalStrength::Weak;
    }
}

std::string WifiBoard::GetWiFiSSid() {
    if (wifi_config_mode_) {
        return "";
    }

    auto& wifi_station = WifiStation::GetInstance();
    if (!wifi_station.IsConnected()) {
        return "";
    }

    return wifi_station.GetSsid();
}

std::string WifiBoard::GetBoardJson() {
    // Set the board type for OTA
    auto& wifi_station = WifiStation::GetInstance();
    std::string board_json = std::string("{\"type\":\"" BOARD_TYPE "\",");
    board_json += "\"name\":\"" BOARD_NAME "\",";
    if (!wifi_config_mode_) {
        board_json += "\"ssid\":\"" + wifi_station.GetSsid() + "\",";
        board_json += "\"rssi\":" + std::to_string(wifi_station.GetRssi()) + ",";
        board_json += "\"channel\":" + std::to_string(wifi_station.GetChannel()) + ",";
        board_json += "\"ip\":\"" + wifi_station.GetIpAddress() + "\",";
    }
    board_json += "\"mac\":\"" + SystemInfo::GetMacAddress() + "\"}";
    return board_json;
}

void WifiBoard::SetPowerSaveMode(bool enabled) {
    auto& wifi_station = WifiStation::GetInstance();
    wifi_station.SetPowerSaveMode(enabled);
}

void WifiBoard::ResetNetConfiguration() {
    // Set a flag and reboot the device to enter the network configuration mode
    {
        Settings settings("wifi", true);
        settings.SetInt("force_ap", 1);
    }
    SetState(WifiState::ConfigMode);
    vTaskDelay(pdMS_TO_TICKS(1000));
    // Reboot the device
    esp_restart();
}

const char* wifiState[] = {"Idle", "Scanning", "Connecting", "Connected", "Failed", "ConfigMode"};
void WifiBoard::SetState(WifiState new_state) {
    if (new_state != current_state_) {
        current_state_ = new_state;
        if (event_callback_) {
            std::string state = std::string("WiFiEvent:") + wifiState[static_cast<int>(new_state)];
            if (new_state == WifiState::ConfigMode) {
                auto& wifi_ap = WifiConfigurationAp::GetInstance();
                std::string hint = Lang::Strings::CONNECT_TO_HOTSPOT;
                hint += wifi_ap.GetSsid();
                hint += Lang::Strings::ACCESS_VIA_BROWSER;
                hint += wifi_ap.GetWebServerUrl();
                hint += "\n\n";
                event_callback_(state, hint);
            } else {
                event_callback_(state, "Ok");
            }
        }
    }
}

bool WifiBoard::NetIsConnected() {
    auto& wifi_station = WifiStation::GetInstance();
    return wifi_station.IsConnected();
}